﻿using System;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;

namespace TechFreak.uapman
{
    internal class Program
    {
        [STAThread]
        internal static void Main(string[] args)
        {
            // We wrap this in a try/catch block, as we absolutely do not want to have any exceptions thrown
            try
            {
                // Parse Arguments
                ParseArguments(args);

                // Check for the Minimum OS Version we support
                if (!OperatingSystem.CheckMinVersion())
                {
                    Console.WriteLine("OS Version is below Major Version {0}. Exiting.", Settings.MinMajorVersion);
                    Environment.Exit(1);
                }

                if (Settings.ConsoleLogEnabled)
                {
                    Console.WriteLine("Retrieving Active Directory DN for User " + Environment.UserDomainName + @"\" + Environment.UserName);
                }


                // Retrieve DN for currently logged-on User
                var objectDn = ActiveDirectory.GetObjectDistinguishedName(ObjectClass.User, ReturnType.DistinguishedName,Environment.UserName, Environment.UserDomainName);
                
                // Retrieve thumbnailPhoto for User
                if (Settings.ConsoleLogEnabled)
                {
                    Console.WriteLine("Retrieving Photo from Active Directory");
                }
                var photo = ActiveDirectory.AttributeValuesByteStream("thumbnailPhoto", objectDn);

                // Do we have a photo?
                if (photo != null && photo.Length > 0)
                {
                    if (Settings.ConsoleLogEnabled)
                    {
                        Console.WriteLine("Found photo. Trying to insert as Account Picture...");
                    }

                    // Create temporary file with AD Photo
                    var tempFileName = Path.GetTempFileName();
                    ImageConverters.ConvertByteArrayToImage(photo).Save(tempFileName, ImageFormat.Bmp);

                    // Set Photo as UserAccountPicture
                    var result = UserAccountPicture.SetUserTile(Environment.UserDomainName + @"\" + Environment.UserName, 0, tempFileName);

                    if (Settings.ConsoleLogEnabled)
                    {
                        Console.WriteLine("Result: " + result);
                    }

                    // Delete temporary file
                    File.Delete(tempFileName);
                }
                // No photo found...
                else
                {
                    if (Settings.ConsoleLogEnabled)
                    {
                        Console.WriteLine("No photo found.");
                    }

                    if (Settings.SetDefaultPicture)
                    {
                        Console.WriteLine("Trying to insert default picture as Account Picture...");

                        if (File.Exists("default.bmp"))
                        {

                            var result = UserAccountPicture.SetUserTile(Environment.UserDomainName + @"\" + Environment.UserName, 0, "default.bmp");
                            if (Settings.ConsoleLogEnabled)
                            {
                                Console.WriteLine("Result: " + result);
                            }
                        }
                        else
                        {
                            if (Settings.ConsoleLogEnabled)
                            {
                                Console.WriteLine("Default picture not found. Exiting.");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (Settings.ConsoleLogEnabled)
                {
                    Console.WriteLine("Error Occured:" + e);
                }
                Environment.Exit(2);
                // Silently fail... after all it's only a picture ;)
            }
        }

        /// <summary>
        /// Parse Arguments
        /// </summary>
        /// <param name="args">Arguments</param>
        internal static void ParseArguments(string[] args)
        {
            foreach (var arg in args)
            {
                ParseSingleArgument(arg);
            }
        }

        /// <summary>
        /// Parse single arguments
        /// </summary>
        /// <param name="arg">Argument to parse</param>
        internal static void ParseSingleArgument(string arg)
        {
            const string prefix = "^(-|--|/|/:)";
            var rVerbose = new Regex(prefix + "(verbose|v)$");
            var rSetDefault = new Regex(prefix + "(default|d|setdefault)$");

            if (rVerbose.IsMatch(arg))
            {
                Settings.ConsoleLogEnabled = true;
                return;
            }

            if (rSetDefault.IsMatch(arg))
            {
                Settings.SetDefaultPicture = true;
                return;
            }
        }
    }
}
